package com.qf.news.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.news.dao.NewsInfoDao;
import com.qf.news.entity.NewsInfo;
import com.qf.news.entity.SearchInfo;
import com.qf.news.service.NewsInfoService;
import com.qf.news.service.NewsTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 新闻信息表(NewsInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-07-20 10:11:38
 */
@Service("newsInfoService")
public class NewsInfoServiceImpl extends ServiceImpl<NewsInfoDao, NewsInfo> implements NewsInfoService {

    /**
     * 操作其他表，必须经过其他表的业务层操作，不能直接操作dao
     */
    @Autowired
    private NewsTypeService newsTypeService;

    @Override
    @Transactional
    public boolean save(NewsInfo entity) {
        //所属分类id
        Integer tid = entity.getTid();
        //给当前分类下的新闻数量+1
        newsTypeService.updateNewsTypeCount(tid, 1);
        return super.save(entity);
    }

    /**
     * 根据关键字搜索列表
     *
     * select * from news_info where
     *              tid = ? and (subject like '%?%' or writer like '%?%')
     *
     * @param searchInfo
     * @return
     */
    @Override
    public List<NewsInfo> listBySearch(SearchInfo searchInfo) {
        return this.query()
                .eq(searchInfo.getTid() != null, "tid", searchInfo.getTid())
                .and(StringUtils.hasLength(searchInfo.getKeyword()), newsInfoQueryWrapper -> {
                   newsInfoQueryWrapper
                           .like("subject", searchInfo.getKeyword())
                           .or()
                           .like("writer", searchInfo.getKeyword());
                }).list();
    }
}

